﻿#include"XQTableExportWidget.h"
#include"XQTaskPool.h"
#include"XQRunnable.h"
#ifdef THIRDPARTY
#include"XExcel.h"
#endif // 
#include"XQStatusBarWidget.h"
#include<QHeaderView>
#include<QTableView>
#include<QCheckBox>
#include<QLineEdit>
#include<QDebug>
XQTableExportWidget::XQTableExportWidget(QWidget* parent)
	:QScrollArea(parent)
{
	init();
}

XQTableExportWidget::~XQTableExportWidget()
{
}

QTableView* XQTableExportWidget::tableView() const
{
	return m_tableView;
}

void XQTableExportWidget::setTableView(QTableView* tableView)
{
	m_tableView = tableView;
}

void XQTableExportWidget::setExportData(QList<XQTablePagingItem>* data)
{
	m_data = data;
}

QStringList XQTableExportWidget::HorizontalTitle() const
{
	auto tableView = this->tableView();
	if (tableView == nullptr)
		return QStringList();
	QStringList list;
	// 获取水平标题并输出
	QHeaderView* hHeader = tableView->horizontalHeader();
	if (hHeader == nullptr)
		return QStringList();
	for (int i = 0; i < hHeader->count(); i++) {
		list << hHeader->model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString();
	}
	return std::move(list);
}

void XQTableExportWidget::start()
{
	XQRunnable* run = XQRunnable::create([=](XQRunnable* Runnable) {if (!Runnable->isInterruptionRequested())exportExcel(Runnable);  });
	m_taskPool->addTask(run);
}

void XQTableExportWidget::stop()
{
	m_taskPool->requestInterruption();
}

void XQTableExportWidget::exportExcel(XQRunnable* Runnable)
{
	auto model = tableView()->model();
	if (model == nullptr)
		return;
	auto rowCount = model->rowCount();//行数
	auto columnCount = model->columnCount();//列数
#ifdef THIRDPARTY
	XExcel excel;
	//是否写入标题
	if (m_ExportTitle->isChecked())
	{
		excel.writeRow(HorizontalTitle());
		emit showMessage("写入标题");
	}
	emit showMessage("写入中,请稍后!!!");
	if(m_data==nullptr)
	{
		for (size_t row = 0; row < rowCount; row++)
		{
			if (Runnable->isInterruptionRequested())
				break;
			QStringList list;
			for (size_t column = 0; column < columnCount; column++)
			{
				auto index = model->index(row, column);
				list << model->data(index).toString();
			}
			excel.writeRow(list);
			m_statusbar->setProgressValueCount(row + 1, rowCount);
		}
	}
	else
	{
		size_t row = 0;
		for (auto& rowData : *m_data)
		{
			if (Runnable->isInterruptionRequested())
				break;
			QStringList list;
			for (auto& data:rowData)
			{
				list << data.first;
			}
			excel.writeRow(list);
			m_statusbar->setProgressValueCount(++row, m_data->count());
		}
	}
	emit showMessage("保存到本地中:"+ m_filePathEdit->text());
	if (!Runnable->isInterruptionRequested())
	{
		excel.save(m_filePathEdit->text());
		emit showMessage("导出本地完成", 5000);
	}
	else
	{
		m_statusbar->setProgressValueCount(m_data->count(), m_data->count());
		emit showMessage("导出取消", 5000);
	}
#endif
	//qInfo() << HorizontalTitle();
}
